package db

import (
	"encoding/json"
	"github.com/xujiajun/nutsdb"
	"time"
)

const flowBucket = "flow"

func InsertDeviceFlowBySendModel(sendMode *SendModel) (int, error) {
	if data, err := json.Marshal(sendMode); err == nil {
		key := []byte(sendMode.DeviceId + "_" + time.Now().Format("20060102150405"))
		if err := db.Update(
			func(tx *nutsdb.Tx) error {
				if err := tx.Put(flowBucket, key, data, 0); err != nil {
					return err
				}
				return nil
			}); err != nil {
			return 0, err
		}
	}
	return len(sendMode.InOutMetrics), nil
}

func DeleteFlow(entry *nutsdb.Entry) error {
	if err := db.Update(
		func(tx *nutsdb.Tx) error {
			if err := tx.Delete(flowBucket, entry.Key); err != nil {
				return err
			}
			return nil
		}); err != nil {
		return err
	}
	return nil
}

func GetAllFlow() ([]*nutsdb.Entry, error) {
	result := make([]*nutsdb.Entry, 0)
	if err := db.View(
		func(tx *nutsdb.Tx) error {
			bucket := flowBucket
			entries, err := tx.GetAll(bucket)
			if err != nil {
				return err
			}

			for _, entry := range entries {
				result = append(result, entry)
			}

			return nil
		}); err != nil {
		return result, err
	}
	return result, nil
}
